// distribution/index/index.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';


Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            // "homeflag": true,
            "name": "事业中心",
        },

        // 可提现金额
        availableMoney: '0.00',

        tip: '展示更多 ∨',
        isShow: false,

        uid: '',
        nickname: '游客',
        avatarUrl: defaultAvatarUrl,
        mobile: '',
        truename: '',

        userInfo: {},
        options: {},

        good_info: {},

        today_order_num: 0,
        total_order_num: 0,
        today_consumer_num: 0,
        total_consumer_num: 0,

        totalStock: 0,
        monthStock: 0
    },



    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        this.init_data(options)
        if (!this.data.uid) {
            util.showToast("请重启小程序获取相关用户数据")
            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                });
                return
            }, 1500);
        }
        await this.getInfomation()
        // await this.getShareGood()
        // await this.queryWmemberInfo()
        // await this.queryBalance()

        await this.getStockInfo()
    },

    init_data(options) {
        this.setData({
            uid: App.globalData.uid,
            // uid: 7486,
            userInfo: App.globalData.userInfo,
            avatarUrl: App.globalData?.fulluserInfo?.avatar || defaultAvatarUrl,
            nickname: App.globalData?.fulluserInfo?.name || '游客',
            options,
        })
    },

    gotoIdentity() {
        util.showLoading("正在跳转...")
        setTimeout(() => {
            wx.navigateTo({
                url: '/distribution/choice/choice?current=1',
                // url: '/pages/home/home',
                success: (result) => {
                    console.log(result);
                },
                fail: (err) => {
                    console.log(err);
                },
                complete: () => {

                }
            });
            util.hideLoading()
        }, 1500);
    },

    // 查询提现人员详细信息
    async queryWmemberInfo() {
        let wDetail = await request.post(api.queryWmemberInfo, { uid: this.data.uid })
        console.log("提现人详情", wDetail);

        // 提现人员详情不显示在页面 无需记录在data中
        this.wDetail = wDetail ? wDetail : {}
        let true_name = this.wDetail?.true_name ? this.wDetail.true_name : ""
        let mobile = this.wDetail?.allin_moblie ? this.wDetail.allin_moblie : ""
        this.setData({
            mobile: this.encryptMobilerNo(mobile),
            truename: this.encryptName(true_name),
        })
    },

    // 点击显示或隐藏详情盒子
    toggleShow() {
        this.setData({
            tip: this.data.isShow ? '展示更多 ∨' : '∧',
            isShow: !this.data.isShow,
        })
    },

    // 跳转提现页面
    gotocash() {
        wx.navigateTo({
            url: '/pages/cash/cash',
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },

    // 跳转分销商品页面
    showMoreGoods() {
        let url = '/distribution/goodlist/goodlist'

        wx.navigateTo({
            url: url,
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },

    // 姓名星号加密 只显示第一位和最后一位 例如：
    // 张三--------- 张 *
    // 王麻子--------- 王 * 子
    // 王二麻子------- 王 ** 子
    encryptName(name) {
        // 加密姓名
        let enName = []
        if (name.length === 0) return ""
        if (name.length === 2) {
            return name[0] + '*'
        } else {
            let num = name.length - 2
            enName.push(name[0])
            for (let i = 0; i < num; i++) {
                enName.push('*')
            }
            enName.push(name[name.length - 1])
            // console.log(enName, enName.join(''))
            return enName.join('')
        }
    },

    encryptMobilerNo(mobile) {
        // 加密身份证号
        let enMobile = []
        enMobile.push(mobile[0])
        enMobile.push(mobile[1])
        enMobile.push(mobile[2])

        for (let i = 0; i < mobile.length - 7; i++) {
            enMobile.push('*')
        }
        enMobile.push(mobile[mobile.length - 4])
        enMobile.push(mobile[mobile.length - 3])
        enMobile.push(mobile[mobile.length - 2])
        enMobile.push(mobile[mobile.length - 1])
        return enMobile.join('')
    },

    // 获取爆款分销商品
    async getShareGood() {
        let params = {
            page: this.page,
            limit: 1,
            // type: this.data.type,
            brand_id: 2
        }

        let res = await request.post(api.goods_list, params)
        console.log("dfsdf", res);

        // 计算最高可赚佣金
        res.forEach(item => {
            item.highestCommision = (item.sell_price * 0.1).toFixed(2)
        });

        console.log(res);
        this.setData({
            good_info: res[0]
        })
    },

    // 获取分销数据（收益数值等）
    async getInfomation() {
        let info = await request.post(api.myinfo, { uid: this.data.uid })
        // console.log(info);
        this.setData({
            myinfo: info
        })
    },

    // 查询会员提现余额
    async queryBalance() {
        let Balance = await request.post(api.checkAllinBalance, { uid: this.data.uid })
        let allAmount = (Balance.allAmount / 100).toFixed(2)
        // console.log("余额", Balance, allAmount);
        this.setData({
            availableMoney: allAmount
        })
    },

    // 跳转分销订单
    gotoOrders(e) {
        let type = e.currentTarget.dataset.type
        wx.navigateTo({
            url: `/distribution/order/order?type=${type}`,
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },

    // 跳转分销客户
    gotoConsumer(e) {
        let type = e.currentTarget.dataset.type
        wx.navigateTo({
            url: `/distribution/consumer/consumer?type=${type}`,
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },

    // 更新分账订单、邀请客户的数量
    async updateCountData() {
        // 两个接口传参一致 可以复用
        let params1 = {
            user_id: this.data.uid,
            type: 1,
            page: 1,
            limit: 1
        }
        let params2 = {
            user_id: this.data.uid,
            type: 0,
            page: 1,
            limit: 1
        }

        let today_order = await request.postall(api.orderAgentlogList, params1)
        let total_order = await request.postall(api.orderAgentlogList, params2)
        let today_consumer = await request.postall(api.queryMymember, params1)
        let total_consumer = await request.postall(api.queryMymember, params2)

        this.setData({
            today_order_num: today_order.count,
            total_order_num: total_order.count,
            today_consumer_num: today_consumer.count,
            total_consumer_num: total_consumer.count,
        })
    },

    // 获取股权数相关信息
    async getStockInfo() {
        if (!this.data.uid) return util.showToast('用户ID丢失 请尝试重新进入小程序')
        let user_finance = await request.postall(api.get_user_finance, { uid: this.data.uid })
        let countInfo = await request.postall(api.stockloglistcount, { uid: this.data.uid })
        let totalStock = user_finance.data?.stock
        let monthStock = countInfo.data

        console.log(totalStock, monthStock);
        this.setData({
            totalStock: totalStock,
            monthStock: monthStock
        })
    },

    gotoShareSort() {
        wx.navigateTo({
            url: '/distribution/sharesort/sharesort',
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        await this.queryWmemberInfo()
        await this.queryBalance()
        await this.updateCountData()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        // let uid = this.uid
        // let id = e.target.dataset.id
        // let title = e.target.dataset.title
        // let imgurl = e.target.dataset.imgurl

        // // console.log('id', id);
        // let sid = `${uid}a${id}a1`

        // let share_path = `/pages/good/detail`;
        // let sharePath = `/pages/home/home?share=${share_path}&sid=${sid}&id=${id}`

        // // console.log(share_path, sharePath);
        // let shareObj = {
        //     title: title,
        //     path: sharePath,
        //     // imageUrl: this.data.detail_data.img,
        //     imageUrl: imgurl,

        //     success: function (res) {
        //         if (res.errMsg == 'shareAppMessage:ok') {
        //             util.showToast('分享成功');
        //         }
        //     },
        //     fail: function (err) {
        //         console.log(err);
        //         util.showToast('分享失败');
        //     },
        // };
        // console.log('shareObj', shareObj);

        // return shareObj;
    }
})